package com.tbsoft.ehr.util;

import java.io.IOException;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.util.Version;
import org.springframework.beans.factory.FactoryBean;

public class EhrIndexWriterFactoryBean implements FactoryBean{
	
	private IndexWriter indexWriter;
	
	@Override
	public synchronized Object getObject() throws Exception {
		if(indexWriter == null){
			IndexWriterConfig iwConfig = new IndexWriterConfig(Version.LUCENE_34,ikAnalyzer);
			iwConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
			indexWriter = new IndexWriter(luceneIndexDirectory,iwConfig);
		}
		return indexWriter;
	}

	@Override
	public Class<IndexWriter> getObjectType() {
		return IndexWriter.class;
	}

	@Override
	public boolean isSingleton() {
		return true;
	}
	private Directory luceneIndexDirectory;
	private Analyzer ikAnalyzer;
	

	public void setLuceneIndexDirectory(Directory luceneIndexDirectory) {
		this.luceneIndexDirectory = luceneIndexDirectory;
	}

	public void setIkAnalyzer(Analyzer ikAnalyzer) {
		this.ikAnalyzer = ikAnalyzer;
	}
	
	public void closeWriter(){
		if(indexWriter != null){
			try {
				indexWriter.close();
			} catch (CorruptIndexException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	

}
